﻿using System.Reflection;
using System.Web;
using Abmemunit.Data;
using Abmemunit.Data.Infrastructure;
using Abmemunit.Domain.Fakes;
using Abmemunit.Services.Security;
using Abmemunit.Services.Users;
using Autofac;
using Autofac.Integration.Mvc;

namespace Abmemunit.Web
{
    public static class Bootstrapper
    {
        public static void Run()
        {
            SetIocContainer();
        }

        private static void SetIocContainer()
        {
            //Implement Autofac

            var builder = new ContainerBuilder();

            // Register MVC controllers using assembly scanning.
            builder.RegisterControllers(Assembly.GetExecutingAssembly());

            builder.Register(c =>
                HttpContext.Current != null ?
                (new HttpContextWrapper(HttpContext.Current) as HttpContextBase) :
                (new FakeHttpContext("~/") as HttpContextBase))
                .As<HttpContextBase>()
                .InstancePerHttpRequest();

            builder.Register(c => c.Resolve<HttpContextBase>().Request).As<HttpRequestBase>()
                .InstancePerHttpRequest();
            builder.Register(c => c.Resolve<HttpContextBase>().Response).As<HttpResponseBase>()
                .InstancePerHttpRequest();
            builder.Register(c => c.Resolve<HttpContextBase>().Server).As<HttpServerUtilityBase>()
                .InstancePerHttpRequest();
            builder.Register(c => c.Resolve<HttpContextBase>().Session).As<HttpSessionStateBase>()
                .InstancePerHttpRequest();

            
            // Register MVC controller dependencies per request.
            builder.RegisterGeneric(typeof(EfRepository<>)).As(typeof(IRepository<>)).InstancePerHttpRequest();
            builder.RegisterType<EncryptionService>().As<IEncryptionService>().InstancePerDependency();
            builder.RegisterType<UserService>().As<IUserService>().InstancePerDependency();
            builder.Register<IDbContext>(c => new AbmemunitContext()).InstancePerLifetimeScope();
            

            var container = builder.Build();
            //for MVC Controller Set the dependency resolver implementation.
            var resolverMvc = new AutofacDependencyResolver(container);
            System.Web.Mvc.DependencyResolver.SetResolver(resolverMvc);

        }

    }
}